{% extends "vmServer/index_server.html" %}

{% block content %}
	<div class="row">
		<div class="col-xs-12">
			<a href="/addInstance/{{vmServer.id}}/">
				<botton class="btn btn-primary  pull-right">
				<i class="icon-arrow-right icon-plus"></i>
						新建虚拟机
				</botton>
			</a>

			<h3 class="header smaller lighter blue">
				<i class="icon-hand-right icon-animated-hand-pointer blue"></i>
				虚拟机实例列表
			</h3>
			<div class="table-header">
				当前宿主机所拥有的虚拟机实例
			</div>

			<div class="table-responsive">
				<table id="sample-table-2" class="table table-striped table-bordered table-hover">
					<thead>
						<tr>
							<th class="center">
								<label>
									<input type="checkbox" class="ace" />
									<span class="lbl"></span>
								</label>
							</th>
							<th>实例名称</th>
							<th class="hidden-480">CPU</th>

							<th>
								<i class="icon-time bigger-110"></i>
								内存(MB)
							</th>

							<th class="hidden-480">状态</th>

							<th class="center col-sm-3">操作</th>
						</tr>
					</thead>

					<tbody>
					{% for ds in inStanceList %}
						<tr>
							<td class="center">
								<label>
									<input type="checkbox" class="ace" />
									<span class="lbl"></span>
								</label>
							</td>
							<td>
								<a href="/viewInstance/{{ds.server_id}}/{{ ds.name }}/">
								{{ ds.name }}
								</a>
							</td>
							<td class="hidden-480">{{ ds.cpu }}</td>
							<td class="hidden-480">{{ ds.mem }}</td>
							<td class="hidden-480">
								{% if ds.status == 1 %}
									 <i class="icon-play green"></i>
								{% elif ds.status == 3 %}
									 <i class="icon-pause orange"></i>
								{% elif ds.status == 5 %}
									 <i class="icon-stop red"></i>
								{% endif %}
							</td>

							<td class="center col-sm-3">
								<div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">
									{% if ds.vnc != '-1'  %}
									<a class="blue" title="VNC" href="/vnc/{{ ds.server_id }}/{{ ds.vnc }}/{{ ds.token }}/" target="_black">
										<i class="icon-desktop bigger-120"></i>
									</a>
									{% else %}
									<a class="blue" title="VNC" href="#" target="_black">
										<i class="icon-desktop bigger-120"></i>
									</a>
									{% endif %}

									<a class="blue" title="启动" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id }},'{{ ds.name }}','start')">
										<i class="icon-play bigger-120 green"></i>
									</a>

									<a class="blue" title="暂停" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id }},'{{ ds.name }}','suspend')">
										<i class="icon-pause bigger-120 orange"></i>
									</a>

									<a class="blue" title="恢复" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id }},'{{ ds.name }}','resume')">
										<i class="icon-play-circle bigger-120 "></i>
									</a>

									<a class="blue" title="重启" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id }},'{{ ds.name }}','reboot')">
										<i class="icon-repeat bigger-120"></i>
									</a>

									<a class="blue" title="关机" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id }},'{{ ds.name }}','shutdown')">
										<i class="icon-stop bigger-120 red"></i>
									</a>

									<a class="red" title="停机" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id}},'{{ ds.name }}','halt')">
										<i class="icon-off bigger-120"></i>
									</a>

									<a class="black" title="快照" href="javascript:" onclick="snapshotInstance(this,{{ ds.server_id }},'{{ ds.name }}','add')">
										<i class="icon-camera bigger-120"></i>
									</a>
									<a class="red" title="删除" href="javascript:" onclick="onBtnHandleIns(this,{{ ds.server_id }},'{{ ds.name }}','delete')">
										<i class="icon-trash  bigger-120"></i>
									</a>
									<a class="black" title="详细" href="/viewInstance/{{ds.server_id}}/{{ ds.name }}/">
										<i class="icon-zoom-in  bigger-120"></i>
									</a>
									<a class="black" title="分配"  data-toggle="modal" data-target="#myModal">
										<i class="icon-external-link  bigger-120"></i>
									</a>
								</div>
							</td>
						</tr>
					{% endfor %}
					</tbody>
				</table>
			</div>
		</div>
	</div>


	<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						&times;
					</button>
					<h4 class="modal-title" id="myModalLabel">
						虚拟机分配
					</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="assignUser">
						<div class="form-group">
							<label class="col-sm-3 control-label no-padding-right" for="form-field-4"><strong>虚拟机选择</strong></label>
							<div class="col-sm-9">
								<select  name="name"  data-placeholder="虚拟机">
									<option value="">选择虚拟机</option>
									{% for ds in inStanceList %}
										<option value="{{ds.name}}">{{ds.name}}</option>
									{% endfor %}
								</select>

							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label no-padding-right" for="form-input-readonly"><strong> 用户</strong> </label>
							<div class="col-sm-9">
								<select name="username">
									{% for ds in userList %}
										<option value="{{ds.username}}">{{ds.username}}</option>
									{% endfor %}
								</select>
							</div>
						</div>
					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭
					</button>
					<button type="button" class="btn btn-primary" onclick="assignVm(this,{{vmServer.id}},'assign')">
						确认
					</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal -->
	</div>

	<script type="text/javascript">
		if("ontouchend" in document) document.write("<script src='/static/js/jquery.mobile.custom.min.js'>"+"<"+"/script>");
	</script>

	<!-- page specific plugin scripts -->

	<script src="/static/js/jquery.dataTables.min.js"></script>
	<script src="/static/js/jquery.dataTables.bootstrap.js"></script>

	<!-- ace scripts -->

	<!-- inline scripts related to this page -->

	<script type="text/javascript">
		jQuery(function($) {
			var oTable1 = $('#sample-table-2').dataTable( {
				"aoColumns": [
				  { "bSortable": false },
				  null, null,null, null, null,
				  { "bSortable": false }
				] }
			);

			$('table th input:checkbox').on('click' , function(){
				var that = this;
				$(this).closest('table').find('tr > td:first-child input:checkbox')
					.each(function(){
						this.checked = that.checked;
						$(this).closest('tr').toggleClass('selected');
					});

			});

			$( "#input-size-slider-4" ).css('width','200px').slider({
				value:1,
				range: "min",
				min: 1,
				max: 8,
				step: 1,
				slide: function( event, ui ) {
					var sizing = ['128', '512', '1024', '2048', '2048', '4096', '8192', '16384', '32768'];
					var val = parseInt(ui.value);
					$('#form-field-4').attr('class', sizing[val]).val(sizing[val]);
				}
			});

			$('[data-rel="tooltip"]').tooltip({placement: tooltip_placement});
			function tooltip_placement(context, source) {
				var $source = $(source);
				var $parent = $source.closest('table')
				var off1 = $parent.offset();
				var w1 = $parent.width();

				var off2 = $source.offset();
				var w2 = $source.width();

				if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';
				return 'left';
			}
		})


		function snapshotInstance(obj,serverId,vmName,op){
			var btnObj = $(obj);
			btnObj.attr('disabled',true);
			window.wxc.xcConfirm("请输入（"+vmName+"）快照名：", window.wxc.xcConfirm.typeEnum.input,{
				onOk:function(result){
					if (result.length == 0){
						/* 如果没有输入字符串则直接退出 */
						return;
					};
					$.ajax({
						type: 'POST',
						url: '/handleSnapshot/',
						data: {
						  "server_id":serverId,
						  "op":op,
						  'vm_name':vmName,
						  'snap_name':result
						},
						success:function(response){
						  	btnObj.removeAttr('disabled');
							if (response["code"]=="200"){
								window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);

							}
							else{
								window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
							}
						},
						error:function(response){
							btnObj.removeAttr('disabled');
							window.wxc.xcConfirm("请求数据错误！", window.wxc.xcConfirm.typeEnum.error);
						},
					});
				}
			});
		}

		function migrateInstance(obj,modalId,serverId,vmName) {
			var btnObj = $(obj);
			btnObj.attr('disabled',true);
			var required = ['vm_tname','server_tid'];
			var server_data = {};
			var form = document.getElementById(modalId);
			for (var i = 0; i < form.length; ++i) {
				var name = form[i].name;
				var value = form[i].value;
				idx = $.inArray(name, required);
				if (idx >= 0 && value.length == 0){
					window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
					return false;
				}
				else if(  value.length != 0 && name.length != 0 ){
					server_data[name] = value;
				};
			};
			server_data['op'] = 'migrate';
			server_data['server_id'] = serverId;
			server_data['vm_name'] = vmName;
			$.ajax({
				dataType: "JSON",
				url:'/handleInstance/', //请求地址
				type:"POST",  //提交类似
				data:server_data,  //提交参数
				success:function(response){
					btnObj.removeAttr('disabled');
					if (response["code"] == 200){
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
					}
					else {
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
					}

				},
				error:function(response){
					btnObj.removeAttr('disabled');
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
			})
		}

		function onBtnHandleIns(obj, server_id,vm_name,op){
			var btnObj = $(obj);
			btnObj.attr('disabled',true);
			if ( op == 'start'){
				var txt=  "是否确认启动？"
			}
			else if ( op == 'shutdown'){
				var txt=  "是否确认关闭？"
			}
			else if( op == 'resume' ){
				var txt=  "是否确认恢复？"
			}
			else if( op == 'suspend' ){
				var txt=  "是否确认暂停？"
			}
			else if( op == 'halt' ){
				var txt=  "是否确认强制关闭？"
			}
			else if( op == 'delete' ){
				var txt=  "是否确认删除？"
			}
			else if( op == 'reboot' ){
				var txt=  "是否确认重启？"
			};
			var option = {
					title: "操作主机("+vm_name+")",
					btn: parseInt("0011",2),
					onOk: function(){
						$.ajax({
							  type: 'POST',
							  url: '/handleInstance/'+server_id+'/',
							  data:{
									"server_id":server_id,
									"op":op,
									"vm_name":vm_name
								},
							  success:function(response){
									btnObj.removeAttr('disabled');
									if (response["code"]=="200"){
										//window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
                                        layer.alert(response["msg"], function() {
                                            layer.closeAll();
                                            window.location.reload();
                                        });
									}
									else{
										//window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
                                        layer.alert(response["msg"], {icon: 2});
									}
							},
							error:function(response){
								btnObj.removeAttr('disabled');
								//window.wxc.xcConfirm("操作失败", window.wxc.xcConfirm.typeEnum.error);
                                layer.alert(response["msg"], {icon: 2});
							},
							});
					},
					onCancel:function(){
					},
					onClose:function(){
					}
				}
			window.wxc.xcConfirm(txt, "custom", option);
		}

		function assignVm(obj,server_id,op) {
			var required = ['name','username'];
			var btnObj = $(obj);
				btnObj.attr('disabled',true);
			var server_data = {};
			var form = document.getElementById('assignUser');
			for (var i = 0; i < form.length; ++i) {
				var name = form[i].name;
				var value = form[i].value;
				idx = $.inArray(name, required);
				if (idx >= 0 && value.length == 0){
					window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
					btnObj.removeAttr('disabled');
					return false;
				}
				else if(  value.length != 0 && name.length != 0 ){
					server_data[name] = value;
				};
			};

			server_data['op'] = op;
			server_data['server'] = server_id;
			$.ajax({
				dataType: "JSON",
				url:'/profile/', //请求地址
				type:"POST",  //提交类似
				data:server_data,  //提交参数
				success:function(response){
					btnObj.removeAttr('disabled');
					if (response["code"] == 200){
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
					}
					else {
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
					}
				},
				error:function(response){
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
			})
		}
	</script>
{% endblock %}
